//
//  Delegate.swift
//  AsyncAwait
//
//  Created by admin on 2021/10/27.
//

import Foundation
import UIKit


class ImagePickerDelegate: NSObject, UINavigationControllerDelegate & UIImagePickerControllerDelegate {
    
    var contination: CheckedContinuation<UIImage?, Never>?

    @MainActor
    func chooseImageFromPhotoLibrary() async throws -> UIImage?{
        
        let vc = UIImagePickerController()
        vc.sourceType = .photoLibrary
        vc.delegate = self
        
        print(">>>>>>>> 图片选择 \(Thread.current)")
        BasicTool.currentViewController()?.present(vc, animated: true, completion: nil)
        
        
        return await withCheckedContinuation({ continuation in
            self.contination = continuation
        })
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
        self.contination?.resume(returning: nil)
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
        self.contination?.resume(returning: image)
        picker.dismiss(animated: true, completion: nil)
    }
}
